package com.itheima.reggie.controller;


import com.itheima.reggie.common.IncludeOtherException;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.filePath}")
    private String filePath;

    @PostMapping("/upload")
    public R upload(MultipartFile file){

        log.debug("文件上传");
        //获取到文件的实际名称
        String OriginalFilename = file.getOriginalFilename();

        //截取到文件后缀名
        String suffix = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));

        //组装新文件名，防止重复
        String newFileName = UUID.randomUUID().toString() + suffix;

        //判断是否存在该路径，不存在则创建
        File file1 = new File(filePath);
        if (!file1.exists()){
            file1.mkdirs();
        }

        try {
            file.transferTo(new File(filePath + newFileName));
        } catch (IOException e) {
            //e.printStackTrace();
            throw new IncludeOtherException("文件上传失败！");
        }
        return R.success(newFileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //拼接文件路径
        String fileName = filePath +name;

        try {
            //将文件读取成为字节数组
            byte[] bytes = FileCopyUtils.copyToByteArray(new File(fileName));
            //通过response写到页面
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
